package com.example.demo.config;

/**
 * Description:
 * User: 故我
 * Date: 2023-11-07
 * Time: 20:12
 */

import com.example.demo.common.AjaxResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

/**
 * 实现统一数据返回的保底类
 * 如果是同一种数据类型，就直接返回，不是就统一成一种数据类型进行返回
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 结果返回 true，就开启下面的返回数据之前的统一处理，false 则反之
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    /**
     * 需要对String这个类型进行特殊处理
     */
    @SneakyThrows  //这个注解就往上一层抛异常
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof AjaxResult) {
            // 是它的子类
            return body;
        }
        if (body instanceof String) {
            return objectMapper.writeValueAsString(AjaxResult.success(body));
        }
        //其他的数据
        return AjaxResult.success(body);
    }
}
